extends RefCounted

var template_path:String

var template_code:String
var source_code:String


func _init(t:String) -> void:
	template_path = t
#----- Methods -----
func clear_code():
	source_code = ''

func create(config_table_path_list:Array):
	var gen_map := {}
	gen_map['CONFIG_TABLE_LIST'] = gen_table_list(config_table_path_list)

	clear_code()
	gen_decription()
	gen_code(gen_map)

func gen_decription():
	var date:String = '{year}-{month}-{day} {hour}:{minute}:{second}'.format(Time.get_datetime_dict_from_system())
	var empty_str = '                                    '
	var left_pad = floor((empty_str.length() - date.length()) / 2)
	var right_pad = ceil((empty_str.length() - date.length()) / 2)
	for i in left_pad:
		date = ' ' + date
	for i in right_pad:
		date = date + ' '
	source_code += "#====================================#\n"
	source_code += "#                                    #\n"
	source_code += "# The file is auto-generated by tool #\n"
	source_code += "#%s#\n" % date
	source_code += "#                                    #\n"
	source_code += "#====================================#\n\n"

func gen_table_list(config_table_path_list:Array):
	var INDENT := 0
	var TEMPLATE := '{0}var {1} := preload("{2}").new()'
	var indent = gen_indent(INDENT)
	var res := ''
	for p in config_table_path_list:
		var path:String = p
		var table_name = path.get_file().trim_suffix('.%s' % path.get_extension())
		res += TEMPLATE.format([indent, table_name, path]) + '\n'
	return res

func gen_code(gen_map:Dictionary):
	read_template()
	source_code += template_code
	for k in gen_map:
		source_code = source_code.replace('{%s}' % k, gen_map[k])

func gen_indent(n:int):
	var res = ''
	for i in n:
		res += '\t'
	return res

func read_template():
	var file = FileAccess.open(template_path, FileAccess.READ)
	var err = FileAccess.get_open_error()
	if err != OK:
		printerr('Can\'t open tempalte file: %s, code: %s' % [template_path, err])
		return
	template_code = file.get_as_text()
	file.close()

func save_to(path):
	var err
	if FileAccess.file_exists(path):
		err = DirAccess.remove_absolute(path)
		if err != OK:
			printerr('Can\'t remove the old file: %s, code: %s' % [path, err])
			return
	var file = FileAccess.open(path, FileAccess.WRITE)
	err = FileAccess.get_open_error()
	if err != OK:
		printerr('Can\'t open file: %s, code: %s' % [path, err])
		return
	file.store_string(source_code)
	file.flush()
	file.close()
#----- Signals -----



